<template>
  <div class="container mx-auto px-4 py-6">
    <div class="flex justify-between items-center mb-6">
      <div class="flex items-center">
        <button @click="$router.back()" class="mr-4 p-2 text-gray-500 hover:text-gray-700 focus:outline-none">
          <ArrowLeftIcon class="h-6 w-6" />
        </button>
        <h2 class="text-2xl font-semibold text-gray-800">
          {{ isEdit ? '编辑借用记录' : '设备借用' }}
        </h2>
      </div>
    </div>

    <div class="max-w-4xl mx-auto">
      <div class="bg-white rounded-xl shadow-lg p-6">
        <form @submit.prevent="handleSubmit" class="space-y-6">
          <!-- 设备选择 -->
          <div>
            <h3 class="text-lg font-medium text-gray-900 mb-4">设备选择</h3>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div>
                <label for="equipmentId" class="block text-sm font-medium text-gray-700">选择设备 *</label>
                <select
                  id="equipmentId"
                  v-model="form.equipmentId"
                  required
                  @change="onEquipmentChange"
                  class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                >
                  <option value="">请选择设备</option>
                  <option v-for="equipment in availableEquipments" :key="equipment.id" :value="equipment.id">
                    {{ equipment.name }} ({{ equipment.code }}) - {{ equipment.status === 'NORMAL' ? '可用' : equipment.status }}
                  </option>
                </select>
                <p v-if="errors.equipmentId" class="mt-1 text-sm text-red-600">{{ errors.equipmentId }}</p>
              </div>

              <div v-if="selectedEquipment">
                <label class="block text-sm font-medium text-gray-700">设备信息</label>
                <div class="mt-1 p-3 bg-gray-50 rounded-md">
                  <p class="text-sm text-gray-900"><strong>设备名称：</strong>{{ selectedEquipment.name }}</p>
                  <p class="text-sm text-gray-900"><strong>设备编号：</strong>{{ selectedEquipment.code }}</p>
                  <p class="text-sm text-gray-900"><strong>设备类别：</strong>{{ selectedEquipment.category }}</p>
                  <p class="text-sm text-gray-900"><strong>规格型号：</strong>{{ selectedEquipment.specification }}</p>
                  <p class="text-sm text-gray-900"><strong>存放位置：</strong>{{ selectedEquipment.location || '未设置' }}</p>
                </div>
              </div>
            </div>
          </div>

          <!-- 借用信息 -->
          <div>
            <h3 class="text-lg font-medium text-gray-900 mb-4">借用信息</h3>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div>
                <label for="borrowerName" class="block text-sm font-medium text-gray-700">借用人姓名 *</label>
                <input
                  type="text"
                  id="borrowerName"
                  v-model="form.borrowerName"
                  required
                  class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                  placeholder="请输入借用人姓名"
                />
                <p v-if="errors.borrowerName" class="mt-1 text-sm text-red-600">{{ errors.borrowerName }}</p>
              </div>

              <div>
                <label for="borrowerPhone" class="block text-sm font-medium text-gray-700">联系电话</label>
                <input
                  type="tel"
                  id="borrowerPhone"
                  v-model="form.borrowerPhone"
                  class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                  placeholder="请输入联系电话"
                />
                <p v-if="errors.borrowerPhone" class="mt-1 text-sm text-red-600">{{ errors.borrowerPhone }}</p>
              </div>

              <div>
                <label for="borrowerDepartment" class="block text-sm font-medium text-gray-700">所属部门</label>
                <input
                  type="text"
                  id="borrowerDepartment"
                  v-model="form.borrowerDepartment"
                  class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                  placeholder="请输入所属部门"
                />
                <p v-if="errors.borrowerDepartment" class="mt-1 text-sm text-red-600">{{ errors.borrowerDepartment }}</p>
              </div>

              <div>
                <label for="borrowDate" class="block text-sm font-medium text-gray-700">借用日期 *</label>
                <input
                  type="date"
                  id="borrowDate"
                  v-model="form.borrowDate"
                  required
                  class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                />
                <p v-if="errors.borrowDate" class="mt-1 text-sm text-red-600">{{ errors.borrowDate }}</p>
              </div>

              <div>
                <label for="expectedReturnDate" class="block text-sm font-medium text-gray-700">预计归还日期 *</label>
                <input
                  type="date"
                  id="expectedReturnDate"
                  v-model="form.expectedReturnDate"
                  required
                  class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                />
                <p v-if="errors.expectedReturnDate" class="mt-1 text-sm text-red-600">{{ errors.expectedReturnDate }}</p>
              </div>

              <div>
                <label for="borrowDays" class="block text-sm font-medium text-gray-700">借用天数</label>
                <input
                  type="number"
                  id="borrowDays"
                  v-model="borrowDays"
                  readonly
                  class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 bg-gray-50 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                />
              </div>
            </div>
          </div>

          <!-- 借用用途 -->
          <div>
            <h3 class="text-lg font-medium text-gray-900 mb-4">借用用途</h3>
            <div>
              <label for="purpose" class="block text-sm font-medium text-gray-700">借用用途 *</label>
              <textarea
                id="purpose"
                v-model="form.purpose"
                required
                rows="4"
                class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                placeholder="请详细说明借用用途"
              ></textarea>
              <p v-if="errors.purpose" class="mt-1 text-sm text-red-600">{{ errors.purpose }}</p>
            </div>
          </div>

          <!-- 其他信息 -->
          <div>
            <h3 class="text-lg font-medium text-gray-900 mb-4">其他信息</h3>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div>
                <label for="contactPerson" class="block text-sm font-medium text-gray-700">联系人</label>
                <input
                  type="text"
                  id="contactPerson"
                  v-model="form.contactPerson"
                  class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                  placeholder="请输入联系人"
                />
                <p v-if="errors.contactPerson" class="mt-1 text-sm text-red-600">{{ errors.contactPerson }}</p>
              </div>

              <div>
                <label for="contactPhone" class="block text-sm font-medium text-gray-700">联系人电话</label>
                <input
                  type="tel"
                  id="contactPhone"
                  v-model="form.contactPhone"
                  class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                  placeholder="请输入联系人电话"
                />
                <p v-if="errors.contactPhone" class="mt-1 text-sm text-red-600">{{ errors.contactPhone }}</p>
              </div>

              <div class="md:col-span-2">
                <label for="note" class="block text-sm font-medium text-gray-700">备注</label>
                <textarea
                  id="note"
                  v-model="form.note"
                  rows="3"
                  class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                  placeholder="请输入备注信息"
                ></textarea>
                <p v-if="errors.note" class="mt-1 text-sm text-red-600">{{ errors.note }}</p>
              </div>
            </div>
          </div>

          <!-- 借用协议 -->
          <div class="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
            <div class="flex">
              <ExclamationTriangleIcon class="h-5 w-5 text-yellow-400 mr-2 mt-0.5" />
              <div>
                <h4 class="text-sm font-medium text-yellow-800">借用协议</h4>
                <div class="mt-2 text-sm text-yellow-700">
                  <ul class="list-disc list-inside space-y-1">
                    <li>借用人应妥善保管设备，不得损坏或丢失</li>
                    <li>借用期间如发生损坏或丢失，借用人应承担相应责任</li>
                    <li>借用期满应及时归还，如需续借请提前申请</li>
                    <li>归还时设备管理员将检查设备状态</li>
                  </ul>
                </div>
              </div>
            </div>
          </div>

          <!-- 提交按钮 -->
          <div class="flex justify-end space-x-3 pt-6 border-t border-gray-200">
            <button
              type="button"
              @click="$router.back()"
              class="px-6 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
            >
              取消
            </button>
            <button
              type="submit"
              :disabled="loading"
              class="px-6 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {{ loading ? '提交中...' : '提交借用申请' }}
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ArrowLeftIcon, ExclamationTriangleIcon } from '@heroicons/vue/24/outline'
import request from '@/utils/request'

const route = useRoute()
const router = useRouter()

const loading = ref(false)
const isEdit = computed(() => !!route.params.id)
const availableEquipments = ref([])
const selectedEquipment = ref(null)

const form = reactive({
  equipmentId: '',
  borrowerName: '',
  borrowerPhone: '',
  borrowerDepartment: '',
  borrowDate: '',
  expectedReturnDate: '',
  borrowPurpose: '',
  contactPerson: '',
  contactPhone: '',
  note: ''
})

const errors = reactive({})

// 计算借用天数
const borrowDays = computed(() => {
  if (form.borrowDate && form.expectedReturnDate) {
    const start = new Date(form.borrowDate)
    const end = new Date(form.expectedReturnDate)
    const diffTime = Math.abs(end - start)
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
    return diffDays
  }
  return 0
})

// 监听借用日期变化，自动设置预计归还日期
watch(() => form.borrowDate, (newDate) => {
  if (newDate && !form.expectedReturnDate) {
    const borrowDate = new Date(newDate)
    const expectedDate = new Date(borrowDate)
    expectedDate.setDate(borrowDate.getDate() + 7) // 默认借用7天
    form.expectedReturnDate = expectedDate.toISOString().split('T')[0]
  }
})

// 设备选择变化
const onEquipmentChange = () => {
  const equipment = availableEquipments.value.find(eq => eq.id == form.equipmentId)
  selectedEquipment.value = equipment
}

// 验证表单
const validateForm = () => {
  // 清空之前的错误
  Object.keys(errors).forEach(key => delete errors[key])
  
  let isValid = true

  if (!form.equipmentId) {
    errors.equipmentId = '请选择设备'
    isValid = false
  }

  if (!form.borrowerName.trim()) {
    errors.borrowerName = '请输入借用人姓名'
    isValid = false
  }

  if (!form.borrowDate) {
    errors.borrowDate = '请选择借用日期'
    isValid = false
  }

  if (!form.expectedReturnDate) {
    errors.expectedReturnDate = '请选择预计归还日期'
    isValid = false
  }

  if (form.borrowDate && form.expectedReturnDate) {
    const borrowDate = new Date(form.borrowDate)
    const expectedDate = new Date(form.expectedReturnDate)
    if (expectedDate <= borrowDate) {
      errors.expectedReturnDate = '预计归还日期必须晚于借用日期'
      isValid = false
    }
  }

  if (!form.borrowPurpose.trim()) {
    errors.borrowPurpose = '请输入借用用途'
    isValid = false
  }

  return isValid
}

// 提交表单
const handleSubmit = async () => {
  if (!validateForm()) {
    return
  }

  try {
    loading.value = true
    
    // 构建请求数据
    const requestData = {
      equipmentId: parseInt(form.equipmentId),
      borrowerName: form.borrowerName,
      borrowerPhone: form.borrowerPhone,
      borrowerDepartment: form.borrowerDepartment,
      borrowDate: form.borrowDate ? `${form.borrowDate}T00:00:00` : null,
      expectedReturnDate: form.expectedReturnDate ? `${form.expectedReturnDate}T00:00:00` : null,
      borrowPurpose: form.borrowPurpose,
      contactPerson: form.contactPerson,
      contactPhone: form.contactPhone,
      note: form.note
    }
    
    if (isEdit.value) {
      // 更新借用记录
      await request.put(`/equipment-borrow/${route.params.id}`, requestData)
      showMessage('借用记录更新成功', 'success')
    } else {
      // 创建借用申请
      await request.post('/equipment-borrow', requestData)
      showMessage('设备借用申请提交成功', 'success')
    }
    
    router.push('/equipment-borrow')
    
  } catch (error) {
    console.error('提交借用申请失败:', error)
    showMessage('提交借用申请失败', 'error')
  } finally {
    loading.value = false
  }
}

// 加载可用设备
const loadAvailableEquipments = async () => {
  try {
    // 调用后端API加载可用设备
    const response = await request.get('/equipment/available')
    availableEquipments.value = response.data || []
    
  } catch (error) {
    console.error('加载可用设备失败:', error)
    showMessage('加载可用设备失败', 'error')
  }
}

// 加载借用记录（编辑时）
const loadBorrowRecord = async () => {
  if (!isEdit.value) return

  try {
    loading.value = true
    const recordId = route.params.id
    
    // 调用真实API加载借用记录
    const response = await request.get(`/equipment-borrow/${recordId}`)
    const record = response.data
    
    // 映射API数据到表单字段
    form.equipmentId = record.equipmentId || ''
    form.borrowerName = record.borrowerName || ''
    form.borrowerPhone = record.borrowerPhone || ''
    form.borrowerDepartment = record.borrowerDepartment || ''
    form.borrowDate = record.borrowDate || ''
    form.expectedReturnDate = record.expectedReturnDate || ''
    form.borrowPurpose = record.borrowPurpose || ''
    form.contactPerson = record.contactPerson || ''
    form.contactPhone = record.contactPhone || ''
    form.note = record.note || ''
    
    onEquipmentChange()
    
  } catch (error) {
    console.error('加载借用记录失败:', error)
    showMessage('加载借用记录失败', 'error')
  } finally {
    loading.value = false
  }
}

// 简单消息显示函数
const showMessage = (message, type = 'info') => {
  const messageEl = document.createElement('div')
  messageEl.className = `fixed top-4 right-4 px-6 py-3 rounded-lg text-white z-50 ${
    type === 'success' ? 'bg-green-500' :
    type === 'warning' ? 'bg-yellow-500' :
    type === 'error' ? 'bg-red-500' :
    'bg-blue-500'
  }`
  messageEl.textContent = message
  document.body.appendChild(messageEl)

  setTimeout(() => {
    if (document.body.contains(messageEl)) {
      document.body.removeChild(messageEl)
    }
  }, 3000)
}

onMounted(() => {
  loadAvailableEquipments()
  loadBorrowRecord()
})
</script>